package com.mgg.gateway.service.rbac.impl;

import com.mgg.common.dao.DaoSupport;
import com.mgg.gateway.service.rbac.RbacService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: lijun
 * @Date: 2018/9/5 10:09
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService{

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private DaoSupport dao;

    @Override
    public Boolean hasPermission(HttpServletRequest request, Authentication authentication){
        boolean hasPermission = false;
        if (authentication == null) {
            return hasPermission;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            //读取用户所拥有权限的所有URL
            String username = ((UserDetails) principal).getUsername();
            try {
                List<String> urls = dao.findForList("AuthMapper.listPermissionUrlsByUsername",username);
                for (String url : urls) {
                    if (antPathMatcher.match(url, request.getRequestURI())) {
                        hasPermission = true;
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                hasPermission = false;
            }
        }
        return hasPermission;
    }

}
